﻿using AF_Application.Interface.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Configuration;
using AF_Cache.Session;
using AF_IOC;

namespace AF_Auth
{
    public class AuthHandler : IHttpHandler
    {
        ISessionCacheProvider SessionCacheProvider = null;
        public AuthHandler()
        {
            SessionCacheProvider = IOC.Instance.Get<ISessionCacheProvider>();
        }

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string authID = context.Request.QueryString["authid"];
            if (!string.IsNullOrEmpty(authID))
            {
                string RequestUrl = "http://auth.afocus.com.cn/AuthService.ashx?cmd=GetAuthInfo&authid=" + authID;
                using (WebClient WC = new WebClient())
                {
                    WC.Encoding = Encoding.UTF8;
                    string result = WC.DownloadString(RequestUrl);
                    string AuthReturnUrl = ConfigurationManager.AppSettings["AuthReturnUrl"].ToString();
                    try
                    {
                        WeixinAuthInfo WAI = Newtonsoft.Json.JsonConvert.DeserializeObject<WeixinAuthInfo>(result);
                        if (WAI != null)
                        {
                            if (!string.IsNullOrEmpty(AuthReturnUrl))
                            {
                                if (SessionCacheProvider.Set<WeixinAuthInfo>(WeiXinAuthHelper.AuthKey, WAI))
                                {
                                    context.Response.Redirect(AuthReturnUrl, false);
                                }
                                else
                                {
                                    throw new Exception("写入授权用户信息失败！");
                                }
                            }
                            else
                            {
                                throw new Exception("请在config中配置AuthReturnUrl（授权成功后回调地址）");
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("用户授权失败，" + result + "，错误：" + ex.Message);
                    }
                }
            }
            else
            {
                context.Response.Write("授权失败，AuthID未正确返回");
            }
        }
    }
}
